import { defineStore } from "pinia";

import { TASK_STATUS, type ITask } from "@/models/task";
import { getCurrentTime, getUniqueId } from "@/utils/tools";

export const useTaskStore = defineStore("task", {
  state: () => ({
    // 任务列表
    list: [],
    // 当前任务详情
    currentTask: {
      id: "",
    },
  }),
  actions: {
    // 创建任务
    handleCreateTask(task: ITask): void {
      const taskSchema: ITask = {
        id: getUniqueId(),
        title: task.title,
        description: task.description,
        createdAt: getCurrentTime(),
        updatedAt: getCurrentTime(),
        status: TASK_STATUS.WAITING,
        startTime: task?.startTime || 0,
        endTime: task?.endTime || 0,
      };
      this.list.push(taskSchema);
    },
    // 删除任务
    handleDeleteTask(id: string): void {
      const targetIndex = this.list.findIndex((ele) => ele.id === id);
      if (targetIndex === -1) return;
      this.list.splice(targetIndex, 1);
    },
    // 修改任务
    handleUpdateTask(item: ITask): void {
      const targetIndex = this.list.findIndex((ele) => ele.id === item.id);
      if (targetIndex === -1) return;
      const targetTask = this.list.find((ele) => ele.id === item.id);
      const data = Object.assign({}, targetTask, item);
      data.updatedAt = getCurrentTime();
      this.list.splice(targetIndex, 1, data);
    },
    // 根据id查询任务
    handleFindTaskById(id: string): ITask {
      const targetTask = this.list.find((ele) => ele.id === id);
      return targetTask?.id ? targetTask : null;
    },
    // 根据关键词语查询任务
    handleFindTaskByKeywords(keywords = ""): ITask {
      const targetTask = this.list.filter((ele) =>
        ele.title.includes(keywords)
      );
      return targetTask || null;
    },
    // 设置当前的任务详情
    handleSetCurrentTaskDetails(task: ITask): void {
      this.currentTask = Object.assign({}, task);
    },
    // 清空当前的任务详情
    handleResetCurrentTask(task: ITask): void {
      this.currentTask = Object.assign({}, task);
    },
  },
  persist: true,
});
